import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { View, Text } from '@tarojs/components';
import "./index.scss"

class Message extends Component {
  constructor(props) {
    super(props);
  }
  render() { 
    let {
      className = "",
      content = "content",
      icon = "success",
    } = this.props
    return (
      <View className={`tipAlert_item ${className}`}>
        <View className={`tipAlert_item_icon tipAlert_item_icon_${icon}`}></View>
        <View className='tipAlert_item_content'>{content}</View>
      </View>
    );
  }
}

class Alert {
  constructor(){
    let rootDom = document.querySelector("#tipAlert_root")
    if(!rootDom){
      rootDom =  document.createElement("div")
      rootDom.id = "tipAlert_root"
      document.body.append(rootDom)
    }
    this.rootDom = rootDom
    this.msgKeyMap = {}
  }
  // 显示
  show = (params = {}) => {
    let rootDom = this.rootDom
    if(!rootDom){
      return new Error("tipAlert没有根节点")
    }
    let props = {
      icon: "success",
      duration: 2000,
      key: rootDom.childNodes.length
    }
    if(typeof(params) === "string"){
      props.content = params
    }else{
      props = {...props, ...params}
    }

    let childRoot = rootDom.querySelector(`.tipAlert_${props.key}`)
    if(!childRoot){
      childRoot = document.createElement("div")
      childRoot.classList.add(`tipAlert_${props.key}`)
    }
    rootDom.append(childRoot)
    ReactDOM.render(<Message {...props} />, childRoot)

    // 清除之前的key的定时
    if(this.msgKeyMap[props.key]){
      clearTimeout(this.msgKeyMap[props.key])
    }

    // duration 为0，不清除节点
    if(props.duration > 0){
      this.msgKeyMap[props.key] = setTimeout(() => {
        childRoot.remove()
        delete this.msgKeyMap[props.key]
      }, props.duration);
    }
  }
  showType = (content, type) => {
    if(Object.prototype.toString.call(content) === "[object Object]"){
      this.show({ icon: type, ...content })
    }else{
      this.show({ content, icon: type })
    }
  }
  success = (content) => {
    this.showType(content, "success")
  }
  error = (content) => {
    this.showType(content, "error")
  }
}

/**
 * @parmas options Object
 * @options icon success | error | info | warning | question | loading
 * @options content 内容
 * @options duration 多久消失（单位s）
 * @options key 唯一标识
 * @options className
 */
export const tipAlert = new Alert()
 